package com.study.lambda;


import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;


/**
 * java8四大内置函数式接口
 * Consumer<T>:消费型接口
 *  void accept(T t);
 * Supplier<T>:供给型接口
 *   T get();
 * Function<T,R>:函数型接口
 *   R apply(T t);
 * Predicate<T>:断言型接口
 *   boolean test(T t)
 * */
public class TestLambda3 {

    /**
     * 消费型接口
     * */
    @Test
    public void test1(){
        this.method1(10000,(t)-> System.out.println("消费金额为:"+t));
    }

    public void method1(Integer money, Consumer<Integer> consumer){
        consumer.accept(money);
    }

    /**
     * 供给型接口
     * */
    @Test
    public void test2(){
        List<Integer> list = method2(10, () -> (int) (Math.random() *100));
        list.forEach(System.out::println);
    }

    public List<Integer> method2(int num, Supplier<Integer> supplier){
        List<Integer> list=new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }

    /**
     * 函数型接口
     * */
    @Test
    public void test3(){
        System.out.println(this.method("今天是个好天气", (str) -> str.substring(0, 5)));
    }

    public String method(String str, Function<String,String> function){
        return function.apply(str);
    }

    /**
     * 断言型接口
     * */
    @Test
    public void test4(){
        List<String> list= Arrays.asList("今天是个","Hello word","22","rrrrrr");
        this.method4(list,(str)->str.length()>3).forEach(System.out::println);
    }

    public List<String> method4(List<String> list, Predicate<String> predicate){
        List<String> data=new ArrayList<>();
        for (String s : list) {
            if(predicate.test(s)){
                data.add(s);
            }
        }
        return data;
    }
}
